package com.xzy.sms.core.adapter.impl.sz;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xzy.sms.core.adapter.SendSmsAdapter;
import com.xzy.sms.core.entity.SendContext;
import com.xzy.sms.exception.SendSmsException;
import com.xzy.sms.web.domain.entity.ChannelConfig;

/**
 * @desc 深圳短信网关
 * @author wjw
 * @time 2017年11月16日下午3:29:41
 */
public class SzSendSmsAdapter implements SendSmsAdapter {
    
    /**
     * 日志对象
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());
    
    @Override
    public void sendSms(SendContext smsContext) throws SendSmsException {
        try {
            ChannelConfig cc = smsContext.getChannelConfig();
            String appId = cc.getAccount();
            String appPassword = cc.getPassword();
            String mobile = smsContext.getMobile();
            String content = smsContext.getContent();
            String soapRequestData = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">"
                + "<soapenv:Header/> <soapenv:Body><tem:SendSMS><tem:App_ID>" + appId + "</tem:App_ID><tem:App_PWD>" + appPassword + "</tem:App_PWD>"
                + "<tem:Biz_Class_ID>07</tem:Biz_Class_ID><tem:Biz_Type_ID>0702</tem:Biz_Type_ID>"
                + "<tem:Biz_Sub_Type_ID>070201</tem:Biz_Sub_Type_ID>" + "<tem:Ext_No>91017</tem:Ext_No><tem:Phone_No>" + mobile + "</tem:Phone_No>"
                + "<tem:Content>" + content + "</tem:Content><tem:Is_Need_Report>0</tem:Is_Need_Report><tem:Cust_ID>0</tem:Cust_ID>"
                + "<tem:App_SMS_Code>qywx</tem:App_SMS_Code></tem:SendSMS></soapenv:Body></soapenv:Envelope>";
                
            String wsUrl = cc.getUrl();
            PostMethod postMethod = new PostMethod(wsUrl);
            byte[] bytes = null;
            bytes = soapRequestData.getBytes("utf-8");
            
            InputStream inputStream = new ByteArrayInputStream(bytes, 0, bytes.length);
            RequestEntity requestEntity = new InputStreamRequestEntity(inputStream, bytes.length, "text/xml; charset=utf-8");
            postMethod.setRequestEntity(requestEntity);
            
            HttpClient httpClient = new HttpClient();
            HttpClientParams params = new HttpClientParams();
            // 避免'Expect: 100-continue' handshake
            params.setParameter(HttpClientParams.USE_EXPECT_CONTINUE, Boolean.FALSE);
            // 设置ws连接超时时间
            params.setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, 2000L);
            httpClient.setParams(params);
            int statusCode = httpClient.executeMethod(postMethod);
            String soapResponseData = "";
            logger.info("statusCode=" + statusCode);
            if (statusCode == 200) {
                soapResponseData = postMethod.getResponseBodyAsString();
                logger.info("soapResponseData=" + soapResponseData);
                String ret = getValue(soapResponseData, "Ret");
                if (!"1".equals(ret)) {
                    throw new RuntimeException("短信网关返回了意外的结果：" + ret);
                }
            } else {
                throw new RuntimeException("请求短信网关时，意外的HTTP结果：" + statusCode);
            }
        } catch (RuntimeException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new SendSmsException(ex);
        }
    }
    
    /**
     * @param xml x
     * @param tag x
     * @return String x
     */
    private String getValue(String xml, String tag) {
        if (xml == null || tag == null || xml.length() < tag.length() * 2) {
            return null;
        }
        String tagStart = "<" + tag + ">";
        String tagEnd = "</" + tag + ">";
        int index = xml.indexOf(tagStart) + tagStart.length();
        int end = xml.indexOf(tagEnd);
        if (end < index) {
            return null;
        }
        return xml.substring(index, end).trim();
    }
}
